package controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import pojo.Classes;
import pojo.Status;
import pojo.Tokens;
import service.ClassesService;
import service.TokenService;
import service.impl.ClassesServiceImpl;
import service.impl.TokenServiceImpl;
import utils.JSONUtils;
import utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/api/class")
@RestController
public class ClassController {

    private ClassesService classesService = new ClassesServiceImpl();
    private TokenService tokenService = new TokenServiceImpl();

    @GetMapping
    public void majorClass(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String majorId = request.getParameter("majorId");
        List<Classes> classesList = classesService.queryAllClassByMajorId(majorId);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put(Status.CODE, Status.OK);
        jsonObject.put(Status.MSG, "系id为" + majorId + "下的所有班级查询成功");
        jsonObject.put("data", classesList);

        JSONUtils.responseJson(response, jsonObject.toJSONString());

    }

    @PostMapping("/create")
    public void create(@RequestBody Classes classes, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String accessToken = request.getHeader("AccessToken");
        Tokens tokens = tokenService.queryByToken(accessToken);

        JSONObject jsonObject = new JSONObject();

        if (TokenUtils.decrypt(tokens)) {
            int i = classesService.registClass(classes);
            if (i == -1) {
                jsonObject.put(Status.CODE, Status.BAD_REQUEST);
                jsonObject.put(Status.MSG, classes.getName() + "班级添加失败");
            } else {
                jsonObject.put(Status.CODE, Status.OK);
                jsonObject.put(Status.MSG, classes.getName() + "班级添加成功");
            }

        } else {
            jsonObject.put(Status.CODE, Status.UNAUTHORIZED);
            jsonObject.put(Status.MSG, "请登录");

        }
        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }


}
